<template>
  <div class="panel-count">
    <el-form ref="formRef" :model="formData" label-width="60" size="large" :rules="rules" status-icon>
      <el-form-item label="账号" prop="name">
        <el-input v-model="formData.name"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" show-password/>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormRules, FormInstance, ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import userLoginStore from '@/store/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'

const formData = reactive<IAccount>({
  name: localCache.getCache('name') || '',
  password: localCache.getCache('password') || ''
})
const rules: FormRules = {
  name: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ]
}

const loginStore = userLoginStore()
// const formRef = ref<FormInstance>()
const formRef = ref<InstanceType<typeof ElForm>>()
  async function loginAction (isRemPwd: boolean) {
  console.log('panel-count', formData.name, formData.password)
  // const valid = await formRef.value?.validate()
  // return valid
  formRef.value?.validate((valid) => {
    if (valid) {
      console.log('验证通过')
      loginStore.loginAccountAction({
        name: formData.name,
        password: formData.password
      }).then((res) => {
        if (isRemPwd) {
          localCache.setCache('name', formData.name)
          localCache.setCache('password', formData.password)
        } else {
          localCache.removeCache('name')
          localCache.removeCache('password')
        }
      })
    } else {
      // console.log('验证失败')
      ElMessage.error('验证失败!')
    }
  })
}

defineExpose({
  loginAction
})

</script>

<style lang="less" scoped>
.panel-count {

}
</style>
